<script lang="ts">
  import { Button } from "$lib/components/ui/button";
  import { Input } from "$lib/components/ui/input";
  import { Label } from "$lib/components/ui/label";
  import { settings } from "$lib/store";
  import { invoke } from '@tauri-apps/api/core';
  import { Settings, Bell, Power, Database, TestTube, Trash2 } from "lucide-svelte";

  let localSettings = $state({ ...$settings });
  let testNotificationSent = $state(false);

  async function saveSettings() {
    settings.set(localSettings);
    // 这里可以添加保存到本地文件的逻辑
    alert('设置已保存！');
  }

  async function toggleAutoStart() {
    try {
      if (localSettings.autoStart) {
        await invoke('enable_autostart');
      } else {
        await invoke('disable_autostart');
      }
      localSettings.autoStart = !localSettings.autoStart;
    } catch (error) {
      console.error('切换开机启动失败:', error);
      alert('切换开机启动失败，请重试');
    }
  }

  async function testNotification() {
    try {
      await invoke('show_notification', {
        title: '日报提醒测试',
        body: '这是一个测试通知，提醒您该写日报了！'
      });
      testNotificationSent = true;
      setTimeout(() => {
        testNotificationSent = false;
      }, 3000);
    } catch (error) {
      console.error('发送测试通知失败:', error);
      alert('发送测试通知失败');
    }
  }

  async function exportData() {
    // 导出日报数据的逻辑
    alert('导出功能开发中...');
  }

  async function importData() {
    // 导入日报数据的逻辑
    alert('导入功能开发中...');
  }

  async function clearAllData() {
    const confirmMessage = `⚠️ 危险操作确认\n\n确定要清空所有日报数据吗？\n\n此操作将永久删除所有日报记录，无法恢复！\n\n请输入 "确认删除" 来继续：`;
    const userInput = prompt(confirmMessage);
    
    if (userInput === '确认删除') {
      try {
        // 通过 reportActions 清空所有数据
        const { reportActions } = await import('$lib/store');
        const { StorageService } = await import('$lib/storage');
        
        const storage = StorageService.getInstance();
        const success = await storage.saveReports([]);
        
        if (success) {
          // 更新前端状态
          await reportActions.loadReports();
          alert('所有日报数据已清空！');
        } else {
          alert('清空失败，请重试');
        }
      } catch (error) {
        console.error('清空数据失败:', error);
        alert('清空失败，请重试');
      }
    } else if (userInput !== null) {
      alert('输入不正确，操作已取消');
    }
  }

  async function showDataLocation() {
    const platform = navigator.platform.toLowerCase();
    let location = '';
    
    if (platform.includes('win')) {
      location = '%LOCALAPPDATA%\\rbao-data\\daily-reports.json';
    } else if (platform.includes('mac')) {
      location = '~/Library/Application Support/rbao-data/daily-reports.json';
    } else {
      location = '~/.local/share/rbao-data/daily-reports.json';
    }
    
    alert(`日报数据存储位置：\n\n${location}\n\n您可以手动备份此文件来保存数据。`);
  }
</script>

<div class="max-w-4xl mx-auto p-6 font-notion">
  <div class="bg-notion-bg border border-notion-border rounded-notion-lg shadow-notion-lg">
    <!-- 标题 -->
    <div class="p-6 border-b border-notion-border-light">
      <h1 class="text-2xl font-bold text-notion-text flex items-center gap-3">
        <Settings class="w-6 h-6" />
        设置
      </h1>
      <p class="text-notion-text-light mt-2">配置您的日报应用偏好设置</p>
    </div>

    <div class="p-6 space-y-8">
      <!-- 开机启动 -->
      <section class="bg-notion-bg-secondary rounded-notion p-6">
        <h2 class="text-lg font-semibold text-notion-text mb-4 flex items-center gap-2">
          <Power class="w-5 h-5" />
          开机启动
        </h2>
        <div class="flex items-center justify-between">
          <div>
            <p class="text-notion-text">开机时自动启动日报程序</p>
            <p class="text-sm text-notion-text-light mt-1">程序将在系统启动时自动运行并最小化到系统托盘</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer">
            <input 
              type="checkbox" 
              bind:checked={localSettings.autoStart}
              onchange={toggleAutoStart}
              class="sr-only peer"
            >
            <div class="w-11 h-6 bg-notion-border peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-notion-accent"></div>
          </label>
        </div>
      </section>

      <!-- 周计划设置 -->
      <section class="bg-notion-bg-secondary rounded-notion p-6">
        <h2 class="text-lg font-semibold text-notion-text mb-4 flex items-center gap-2">
          <Bell class="w-5 h-5" />
          周计划转换
        </h2>
        
        <div class="space-y-4">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-notion-text">自动转换周计划</p>
              <p class="text-sm text-notion-text-light mt-1">周六时自动将明日计划转换为下周工作计划</p>
            </div>
            <label class="relative inline-flex items-center cursor-pointer">
              <input 
                type="checkbox" 
                bind:checked={localSettings.autoConvertWeekly}
                class="sr-only peer"
              >
              <div class="w-11 h-6 bg-notion-border peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-notion-accent"></div>
            </label>
          </div>

          <div class="flex items-center justify-between">
            <div>
              <p class="text-notion-text">显示转换提醒</p>
              <p class="text-sm text-notion-text-light mt-1">周末时显示转换提醒通知</p>
            </div>
            <label class="relative inline-flex items-center cursor-pointer">
              <input 
                type="checkbox" 
                bind:checked={localSettings.showWeeklyNotice}
                class="sr-only peer"
              >
              <div class="w-11 h-6 bg-notion-border peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-notion-accent"></div>
            </label>
          </div>
        </div>
      </section>

      <!-- 提醒设置 -->
      <section class="bg-notion-bg-secondary rounded-notion p-6">
        <h2 class="text-lg font-semibold text-notion-text mb-4 flex items-center gap-2">
          <Bell class="w-5 h-5" />
          提醒设置
        </h2>
        
        <div class="space-y-4">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-notion-text">启用定时提醒</p>
              <p class="text-sm text-notion-text-light mt-1">每天在此时间弹出日报窗口</p>
            </div>
            <label class="relative inline-flex items-center cursor-pointer">
              <input 
                type="checkbox" 
                bind:checked={localSettings.enableReminder}
                class="sr-only peer"
              >
              <div class="w-11 h-6 bg-notion-border peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-notion-accent"></div>
            </label>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="space-y-2">
              <Label for="reminderTime" class="text-notion-text">提醒时间</Label>
              <div class="flex items-center gap-2">
                <Input
                  id="reminderTime"
                  type="time"
                  bind:value={localSettings.reminderTime}
                  class="border-notion-border focus:border-notion-accent rounded-notion"
                />
                <span class="text-sm text-notion-text-light">每天在此时间弹出日报窗口</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- 窗口设置 -->
      <section class="bg-notion-bg-secondary rounded-notion p-6">
        <h2 class="text-lg font-semibold text-notion-text mb-4">窗口设置</h2>
        
        <div class="space-y-4">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-notion-text">窗口总是置顶</p>
              <p class="text-sm text-notion-text-light mt-1">日报窗口将始终显示在其他窗口之上</p>
            </div>
            <label class="relative inline-flex items-center cursor-pointer">
              <input 
                type="checkbox" 
                class="sr-only peer"
              >
              <div class="w-11 h-6 bg-notion-border peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-notion-accent"></div>
            </label>
          </div>

          <div class="flex items-center justify-between">
            <div>
              <p class="text-notion-text">关闭时最小化到系统托盘</p>
              <p class="text-sm text-notion-text-light mt-1">点击关闭按钮会保留在dock栏/任务栏，只有关闭窗口时才会隐藏到托盘</p>
            </div>
            <label class="relative inline-flex items-center cursor-pointer">
              <input 
                type="checkbox" 
                checked
                class="sr-only peer"
              >
              <div class="w-11 h-6 bg-notion-accent peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-notion-accent"></div>
            </label>
          </div>
        </div>
      </section>

      <!-- 数据管理 -->
      <section class="bg-notion-bg-secondary rounded-notion p-6">
        <h2 class="text-lg font-semibold text-notion-text mb-4 flex items-center gap-2">
          <Database class="w-5 h-5" />
          数据管理
        </h2>
        
        <div class="space-y-4">
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <Button 
              onclick={exportData}
              variant="outline"
              class="border-notion-border hover:bg-notion-bg-hover text-notion-text rounded-notion"
            >
              导出日报数据
            </Button>
            <Button 
              onclick={importData}
              variant="outline"
              class="border-notion-border hover:bg-notion-bg-hover text-notion-text rounded-notion"
            >
              导入日报数据
            </Button>
            <Button 
              onclick={showDataLocation}
              variant="outline"
              class="border-notion-border hover:bg-notion-bg-hover text-notion-text rounded-notion"
            >
              查看存储位置
            </Button>
          </div>
          
          <div class="pt-4 border-t border-notion-border-light">
            <Button 
              onclick={clearAllData}
              variant="outline"
              class="border-red-300 hover:bg-red-50 text-red-600 rounded-notion w-full md:w-auto"
            >
              <Trash2 class="w-4 h-4 mr-2" />
              清空所有数据
            </Button>
            <p class="text-xs text-red-500 mt-2">⚠️ 危险操作：将永久删除所有日报数据</p>
          </div>
        </div>
      </section>

      <!-- 功能测试 -->
      <section class="bg-notion-bg-secondary rounded-notion p-6">
        <h2 class="text-lg font-semibold text-notion-text mb-4 flex items-center gap-2">
          <TestTube class="w-5 h-5" />
          功能测试
        </h2>
        
        <div class="flex items-center gap-4">
          <Button 
            onclick={testNotification}
            variant="outline"
            class="border-notion-border hover:bg-notion-bg-hover text-notion-text rounded-notion flex items-center gap-2"
          >
            <Bell class="w-4 h-4" />
            {testNotificationSent ? '通知已发送' : '测试提醒功能'}
          </Button>
          <span class="text-sm text-notion-text-light">立即触发提醒窗口</span>
        </div>
      </section>

      <!-- 关于 -->
      <section class="bg-notion-bg-secondary rounded-notion p-6">
        <h2 class="text-lg font-semibold text-notion-text mb-4">关于</h2>
        <div class="text-notion-text-light">
          <p class="mb-2"><strong class="text-notion-text">日报小程序</strong> v1.0.0</p>
          <p class="text-sm">基于 Tauri v2 + Svelte 5 + shadcn-svelte 构建</p>
          <p class="text-sm mt-1">轻量级桌面日报应用，帮助您记录每日工作内容</p>
        </div>
      </section>

      <!-- 保存按钮 -->
      <div class="flex justify-end pt-4 border-t border-notion-border-light">
        <Button 
          onclick={saveSettings}
          class="bg-notion-accent hover:bg-notion-accent/90 text-white px-6 py-2 rounded-notion shadow-notion transition-all duration-200 hover:shadow-notion-hover"
        >
          保存设置
        </Button>
      </div>
    </div>
  </div>
</div>
